<template>
  <div class="flex justify-center items-center h-screen bg-white">
    <div ref="container" class="border container" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import jspreadsheet from 'jspreadsheet-ce'
import 'jspreadsheet-ce/dist/jspreadsheet.css'

import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'

const container = ref(null)
let jspInstance

// 创建 Yjs 文档
const ydoc = new Y.Doc()
const provider = new WebsocketProvider('ws://192.168.5.63:1234', 'spreadsheet-room', ydoc)
const yArray = ydoc.getArray('sheet')

// 初始化协同数据（10 行 5 列）
if (yArray.length === 0) {
  const emptyData = Array.from({ length: 50 }, () => Array.from({ length: 26 }, () => ''))
  yArray.push(emptyData)
}

onMounted(() => {
  nextTick(() => {
    // 初始化表格
    jspInstance = jspreadsheet(container.value, {
      data: yArray.toArray(),
      columns: Array.from({ length: 5 }, () => ({ type: 'text' })),
      minDimensions: [5, 10],
      onchange: (instanceEl, cell, x, y, value) => {
        // 使用 jspInstance，而不是 onchange 提供的 instanceEl
        const currentData = jspInstance.getData()
        yArray.delete(0, yArray.length)
        yArray.insert(0, currentData)
      }
    })


    // Yjs 发生变更时更新表格
    const syncFromYjs = () => {
      const shared = yArray.toArray()
      // 直接刷新 jspreadsheet
      jspInstance.options.data = shared
      jspInstance.refresh()
    }

    yArray.observeDeep(syncFromYjs)
  })
})
</script>

<style scoped>
body {
  font-family: sans-serif;
}

.container {
  width: 100% !important;
  height: 600px !important;
}

:deep(.jexcel_content) {
  width: 100% !important;
}
:deep(.jexcel) {
  width: 100% !important;
}
</style>
